/**
 * 文件上传中间件
 * PC微信聊天应用 - 处理文件上传
 */

const multer = require('multer');
const path = require('path');
const fs = require('fs');
const File = require('../models/File');

// 确保上传目录存在
const uploadDir = process.env.UPLOAD_DIR || 'uploads';
const uploadsPath = path.join(__dirname, '..', uploadDir);

// 创建上传目录结构
const createUploadDirs = () => {
  const dirs = [
    path.join(uploadsPath, 'images'),
    path.join(uploadsPath, 'videos'),
    path.join(uploadsPath, 'audios'),
    path.join(uploadsPath, 'documents'),
    path.join(uploadsPath, 'others')
  ];

  dirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
  });
};

// 初始化上传目录
createUploadDirs();

// 存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    let subDir = 'others';
    
    if (file.mimetype.startsWith('image/')) {
      subDir = 'images';
    } else if (file.mimetype.startsWith('video/')) {
      subDir = 'videos';
    } else if (file.mimetype.startsWith('audio/')) {
      subDir = 'audios';
    } else if (
      file.mimetype.includes('pdf') ||
      file.mimetype.includes('document') ||
      file.mimetype.includes('spreadsheet') ||
      file.mimetype.includes('presentation') ||
      file.mimetype.includes('text')
    ) {
      subDir = 'documents';
    }
    
    const destPath = path.join(uploadsPath, subDir);
    cb(null, destPath);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const uniqueName = File.generateUniqueFileName(file.originalname);
    cb(null, uniqueName);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 检查文件类型
  const allowedTypes = process.env.ALLOWED_FILE_TYPES 
    ? process.env.ALLOWED_FILE_TYPES.split(',')
    : [];
    
  if (File.validateFileType(file.mimetype, allowedTypes)) {
    cb(null, true);
  } else {
    cb(new Error(`不支持的文件类型: ${file.mimetype}`), false);
  }
};

// 创建multer实例
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: parseInt(process.env.MAX_FILE_SIZE) || 50 * 1024 * 1024, // 默认50MB
    files: 5 // 最多5个文件
  }
});

/**
 * 单文件上传中间件
 */
const uploadSingle = (fieldName = 'file') => {
  return (req, res, next) => {
    const singleUpload = upload.single(fieldName);
    
    singleUpload(req, res, (err) => {
      if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_FILE_SIZE') {
          return res.status(400).json({
            success: false,
            message: '文件大小超出限制'
          });
        }
        if (err.code === 'LIMIT_FILE_COUNT') {
          return res.status(400).json({
            success: false,
            message: '文件数量超出限制'
          });
        }
        return res.status(400).json({
          success: false,
          message: `上传错误: ${err.message}`
        });
      } else if (err) {
        return res.status(400).json({
          success: false,
          message: err.message
        });
      }
      
      next();
    });
  };
};

/**
 * 多文件上传中间件
 */
const uploadMultiple = (fieldName = 'files', maxCount = 5) => {
  return (req, res, next) => {
    const multipleUpload = upload.array(fieldName, maxCount);
    
    multipleUpload(req, res, (err) => {
      if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_FILE_SIZE') {
          return res.status(400).json({
            success: false,
            message: '文件大小超出限制'
          });
        }
        if (err.code === 'LIMIT_FILE_COUNT') {
          return res.status(400).json({
            success: false,
            message: '文件数量超出限制'
          });
        }
        return res.status(400).json({
          success: false,
          message: `上传错误: ${err.message}`
        });
      } else if (err) {
        return res.status(400).json({
          success: false,
          message: err.message
        });
      }
      
      next();
    });
  };
};

/**
 * 处理上传后的文件信息
 */
const processUploadedFile = async (req, res, next) => {
  try {
    if (!req.file && !req.files) {
      return res.status(400).json({
        success: false,
        message: '没有上传文件'
      });
    }

    const userId = req.user.id;
    const files = req.files || [req.file];
    const processedFiles = [];

    for (const file of files) {
      // 保存文件信息到数据库
      const fileData = {
        originalName: file.originalname,
        storedName: file.filename,
        filePath: file.path,
        fileSize: file.size,
        fileType: File.getFileType(file.mimetype),
        mimeType: file.mimetype,
        uploadedBy: userId
      };

      const fileId = await File.create(fileData);

      // 根据文件类型生成正确的URL路径
      let subDir = 'others';
      if (file.mimetype.startsWith('image/')) {
        subDir = 'images';
      } else if (file.mimetype.startsWith('video/')) {
        subDir = 'videos';
      } else if (file.mimetype.startsWith('audio/')) {
        subDir = 'audios';
      } else if (
        file.mimetype.includes('pdf') ||
        file.mimetype.includes('document') ||
        file.mimetype.includes('spreadsheet') ||
        file.mimetype.includes('presentation') ||
        file.mimetype.includes('text')
      ) {
        subDir = 'documents';
      }

      processedFiles.push({
        id: fileId,
        originalName: file.originalname,
        storedName: file.filename,
        fileSize: file.size,
        fileType: fileData.fileType,
        mimeType: file.mimetype,
        url: `/api/files/${subDir}/${file.filename}`
      });
    }

    req.uploadedFiles = processedFiles;
    next();
  } catch (error) {
    console.error('处理上传文件错误:', error);
    res.status(500).json({
      success: false,
      message: '处理上传文件失败'
    });
  }
};

/**
 * 图片上传专用中间件
 */
const uploadImage = multer({
  storage: multer.diskStorage({
    destination: path.join(uploadsPath, 'images'),
    filename: (req, file, cb) => {
      const uniqueName = File.generateUniqueFileName(file.originalname);
      cb(null, uniqueName);
    }
  }),
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  },
  limits: {
    fileSize: 10 * 1024 * 1024 // 图片限制10MB
  }
}).single('image');

/**
 * 头像上传中间件
 */
const uploadAvatar = (req, res, next) => {
  uploadImage(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(400).json({
          success: false,
          message: '头像文件大小不能超过10MB'
        });
      }
    } else if (err) {
      return res.status(400).json({
        success: false,
        message: err.message
      });
    }
    
    next();
  });
};

/**
 * 清理临时文件
 */
const cleanupTempFiles = (files) => {
  if (!files) return;
  
  const fileList = Array.isArray(files) ? files : [files];
  
  fileList.forEach(file => {
    if (file && file.path) {
      fs.unlink(file.path, (err) => {
        if (err) console.error('清理临时文件错误:', err);
      });
    }
  });
};

module.exports = {
  upload,
  uploadSingle,
  uploadMultiple,
  processUploadedFile,
  uploadAvatar,
  cleanupTempFiles,
  uploadsPath
};
